// 桌面环境模块 - 整合OriginOS风格桌面到图形子系统
// 仅使用safe Rust

#![forbid(unsafe_code)]

use std::sync::Arc;
use std::sync::Mutex;
use std::sync::RwLock;
use std::collections::{HashMap, VecDeque};
use std::thread;
use std::time::Duration;
use log::{info, warn, error, debug};

// 导入核心服务和类型
use super::graphics_subsystem::{GraphicsSubsystem, GraphicsSubsystemError};
use super::kuikly_service::{KuiklyUIService, KuiklyError};
use super::{Capability, CapabilityId};

// 应用程序信息
#[derive(Debug, Clone)]
pub struct AppInfo {
    pub app_id: String,
    pub name: String,
    pub icon_path: String,
    pub executable_path: String,
    pub description: String,
    pub category: String,
}

// 应用程序状态
#[derive(Debug, Clone, PartialEq)]
enum AppState {
    Running,
    Stopped,
    Starting,
    Stopping,
}

// 运行中的应用程序
struct RunningApp {
    app_id: String,
    app_info: AppInfo,
    window_id: u64,
    state: AppState,
    process_id: Option<u64>,
}

// Dock项类型
#[derive(Debug, Clone, PartialEq)]
enum DockItemType {
    App(String), // app_id
    Shortcut(String), // path
    Separator,
}

// Dock项
struct DockItem {
    item_type: DockItemType,
    position: u32,
    visible: bool,
    hovered: bool,
}

// 桌面环境错误类型
#[derive(Debug, Clone, PartialEq)]
pub enum DesktopEnvironmentError {
    InitializationFailed,
    GraphicsSubsystemError(GraphicsSubsystemError),
    KuiklyError(KuiklyError),
    InvalidParameter,
    AppNotFound,
    AppAlreadyRunning,
    WindowNotFound,
    OperationFailed,
}

// 桌面环境 - 整合OriginOS风格桌面
pub struct DesktopEnvironment {
    graphics_subsystem: Arc<Mutex<GraphicsSubsystem>>,
    kuikly_service: Arc<Mutex<KuiklyUIService>>,
    mem_cap: Capability,
    running_apps: RwLock<HashMap<String, RunningApp>>,
    app_registry: RwLock<HashMap<String, AppInfo>>,
    dock_items: RwLock<Vec<DockItem>>,
    // 桌面配置
    config: RwLock<DesktopConfig>,
    // 系统状态
    initialized: bool,
    running: bool,
    // 主循环线程
    main_loop_thread: Option<thread::JoinHandle<()>>,
    // 桌面背景窗口ID
    desktop_background_window: Option<u64>,
    // 桌面层叠顺序管理器
    layer_manager: RwLock<LayerManager>,
}

// 桌面配置
#[derive(Debug, Clone)]
struct DesktopConfig {
    wallpaper_path: String,
    show_dock: bool,
    dock_position: DockPosition,
    dock_size: u32,
    auto_hide_dock: bool,
    show_desktop_icons: bool,
    grid_size: (u32, u32), // (columns, rows)
    icon_size: u32,
    // OriginOS风格特有配置
    enable_animations: bool,
    enable_gestures: bool,
    enable_app_drawer: bool,
    app_drawer_theme: String,
    // HaikuOS风格配置
    use_haiku_window_manager: bool,
}

// Dock位置
#[derive(Debug, Clone, Copy, PartialEq)]
enum DockPosition {
    Bottom,
    Left,
    Right,
    Top,
}

// 层叠管理器
struct LayerManager {
    layers: Vec<Layer>,
    active_layer: u32,
}

// 图层
struct Layer {
    id: u32,
    name: String,
    z_order: i32,
    visible: bool,
    opacity: f32,
}

impl DesktopEnvironment {
    // 创建新的桌面环境
    pub fn new(
        graphics_subsystem: Arc<Mutex<GraphicsSubsystem>>,
        kuikly_service: Arc<Mutex<KuiklyUIService>>,
        mem_cap: Capability
    ) -> Result<Self, String> {
        Ok(DesktopEnvironment {
            graphics_subsystem,
            kuikly_service,
            mem_cap,
            running_apps: RwLock::new(HashMap::new()),
            app_registry: RwLock::new(HashMap::new()),
            dock_items: RwLock::new(Vec::new()),
            config: RwLock::new(DesktopConfig {
                wallpaper_path: "default_wallpaper.jpg".to_string(),
                show_dock: true,
                dock_position: DockPosition::Bottom,
                dock_size: 64,
                auto_hide_dock: true,
                show_desktop_icons: true,
                grid_size: (5, 4),
                icon_size: 48,
                // OriginOS风格特有配置
                enable_animations: true,
                enable_gestures: true,
                enable_app_drawer: true,
                app_drawer_theme: "originos_light".to_string(),
                // HaikuOS风格配置
                use_haiku_window_manager: true,
            }),
            initialized: false,
            running: false,
            main_loop_thread: None,
            desktop_background_window: None,
            layer_manager: RwLock::new(LayerManager {
                layers: Vec::new(),
                active_layer: 0,
            }),
        })
    }
    
    // 初始化桌面环境
    pub fn initialize(&mut self) -> Result<(), DesktopEnvironmentError> {
        info!("Initializing OriginOS-style Desktop Environment");
        
        // 初始化图层管理器
        self.initialize_layer_manager()?;
        
        // 创建桌面背景窗口
        self.create_desktop_background()?;
        
        // 初始化应用程序注册表
        self.initialize_app_registry()?;
        
        // 初始化Dock栏
        self.initialize_dock()?;
        
        self.initialized = true;
        info!("OriginOS-style Desktop Environment initialized successfully");
        Ok(())
    }
    
    // 初始化图层管理器
    fn initialize_layer_manager(&mut self) -> Result<(), DesktopEnvironmentError> {
        let mut layer_manager = self.layer_manager.write().unwrap();
        
        // 创建默认图层
        layer_manager.layers = vec![
            Layer {
                id: 0,
                name: "Background".to_string(),
                z_order: -1000,
                visible: true,
                opacity: 1.0,
            },
            Layer {
                id: 1,
                name: "Desktop Icons".to_string(),
                z_order: -900,
                visible: true,
                opacity: 1.0,
            },
            Layer {
                id: 2,
                name: "Applications".to_string(),
                z_order: 0,
                visible: true,
                opacity: 1.0,
            },
            Layer {
                id: 3,
                name: "Dock".to_string(),
                z_order: 1000,
                visible: true,
                opacity: 1.0,
            },
            Layer {
                id: 4,
                name: "Top Bar".to_string(),
                z_order: 2000,
                visible: true,
                opacity: 1.0,
            },
            Layer {
                id: 5,
                name: "Notifications".to_string(),
                z_order: 3000,
                visible: true,
                opacity: 1.0,
            },
        ];
        
        layer_manager.active_layer = 2;
        
        Ok(())
    }
    
    // 创建桌面背景窗口
    fn create_desktop_background(&mut self) -> Result<(), DesktopEnvironmentError> {
        let graphics_subsystem = self.graphics_subsystem.lock().map_err(|_| {
            DesktopEnvironmentError::InitializationFailed
        })?;
        
        // 获取主显示器尺寸
        let primary_display = { 
            let display_manager = graphics_subsystem.display_manager.read().unwrap();
            display_manager.primary_display
        };
        
        let (width, height) = {
            let display_manager = graphics_subsystem.display_manager.read().unwrap();
            if let Some(display) = display_manager.displays.get(&primary_display) {
                (display.width, display.height)
            } else {
                (1920, 1080) // 默认尺寸
            }
        };
        
        // 创建背景窗口
        let window_id = graphics_subsystem.create_window(
            "Desktop Background",
            0, 0, 
            width, height
        ).map_err(|e| {
            DesktopEnvironmentError::GraphicsSubsystemError(e)
        })?;
        
        // 将窗口设置为最底层
        // 注意：这里需要在GraphicsSubsystem中实现set_window_layer方法
        
        self.desktop_background_window = Some(window_id);
        
        // 通知Kuikly服务创建桌面背景
        self.kuikly_service.lock().map_err(|_| {
            DesktopEnvironmentError::InitializationFailed
        })?
        .notify_window_created(window_id, "Desktop Background", 0, 0, width, height)
        .map_err(|e| {
            DesktopEnvironmentError::KuiklyError(e)
        })?;
        
        info!("Created desktop background window: {}", window_id);
        
        Ok(())
    }
    
    // 初始化应用程序注册表
    fn initialize_app_registry(&mut self) -> Result<(), DesktopEnvironmentError> {
        let mut app_registry = self.app_registry.write().unwrap();
        
        // 添加一些示例应用
        app_registry.insert("com.zenrs.browser".to_string(), AppInfo {
            app_id: "com.zenrs.browser".to_string(),
            name: "Browser".to_string(),
            icon_path: "icons/browser.png".to_string(),
            executable_path: "/system/apps/browser".to_string(),
            description: "Web browser application".to_string(),
            category: "Internet".to_string(),
        });
        
        app_registry.insert("com.zenrs.files".to_string(), AppInfo {
            app_id: "com.zenrs.files".to_string(),
            name: "Files".to_string(),
            icon_path: "icons/files.png".to_string(),
            executable_path: "/system/apps/files".to_string(),
            description: "File manager application".to_string(),
            category: "System".to_string(),
        });
        
        app_registry.insert("com.zenrs.terminal".to_string(), AppInfo {
            app_id: "com.zenrs.terminal".to_string(),
            name: "Terminal".to_string(),
            icon_path: "icons/terminal.png".to_string(),
            executable_path: "/system/apps/terminal".to_string(),
            description: "Terminal emulator".to_string(),
            category: "System".to_string(),
        });
        
        app_registry.insert("com.zenrs.calculator".to_string(), AppInfo {
            app_id: "com.zenrs.calculator".to_string(),
            name: "Calculator".to_string(),
            icon_path: "icons/calculator.png".to_string(),
            executable_path: "/system/apps/calculator".to_string(),
            description: "Calculator application".to_string(),
            category: "Utilities".to_string(),
        });
        
        info!("Initialized app registry with {} applications", app_registry.len());
        
        Ok(())
    }
    
    // 初始化Dock栏
    fn initialize_dock(&mut self) -> Result<(), DesktopEnvironmentError> {
        let mut dock_items = self.dock_items.write().unwrap();
        
        // 添加默认Dock项（基于OriginOS风格）
        dock_items.push(DockItem {
            item_type: DockItemType::App("com.zenrs.browser".to_string()),
            position: 0,
            visible: true,
            hovered: false,
        });
        
        dock_items.push(DockItem {
            item_type: DockItemType::App("com.zenrs.files".to_string()),
            position: 1,
            visible: true,
            hovered: false,
        });
        
        dock_items.push(DockItem {
            item_type: DockItemType::App("com.zenrs.terminal".to_string()),
            position: 2,
            visible: true,
            hovered: false,
        });
        
        dock_items.push(DockItem {
            item_type: DockItemType::Separator,
            position: 3,
            visible: true,
            hovered: false,
        });
        
        info!("Initialized dock with {} items", dock_items.len());
        
        // 通知Kuikly服务创建Dock栏
        self.kuikly_service.lock().map_err(|_| {
            DesktopEnvironmentError::InitializationFailed
        })?
        .notify_dock_created()
        .map_err(|e| {
            DesktopEnvironmentError::KuiklyError(e)
        })?;
        
        Ok(())
    }
    
    // 启动桌面环境
    pub fn start(&mut self) -> Result<(), DesktopEnvironmentError> {
        if !self.initialized {
            return Err(DesktopEnvironmentError::InitializationFailed);
        }
        
        self.running = true;
        
        // 启动主循环线程
        let graphics_subsystem = Arc::clone(&self.graphics_subsystem);
        let kuikly_service = Arc::clone(&self.kuikly_service);
        let running_apps = Arc::clone(&self.running_apps);
        let app_registry = Arc::clone(&self.app_registry);
        let dock_items = Arc::clone(&self.dock_items);
        let running = Arc::new(std::sync::atomic::AtomicBool::new(true));
        let running_clone = Arc::clone(&running);
        
        self.main_loop_thread = Some(thread::spawn(move || {
            // 桌面环境主循环
            while running_clone.load(std::sync::atomic::Ordering::Relaxed) {
                // 处理桌面事件
                // 例如：用户点击桌面图标、Dock栏交互等
                
                // 更新Dock栏状态
                // 例如：根据鼠标位置显示/隐藏Dock栏
                
                // 更新运行中的应用程序状态
                // 例如：检查应用程序是否崩溃
                
                // 短暂休眠，避免CPU占用过高
                thread::sleep(Duration::from_millis(33)); // 约30fps
            }
            
            info!("Desktop environment main loop stopped");
        }));
        
        info!("OriginOS-style Desktop Environment started successfully");
        Ok(())
    }
    
    // 停止桌面环境
    pub fn stop(&mut self) -> Result<(), DesktopEnvironmentError> {
        if !self.running {
            return Ok(());
        }
        
        self.running = false;
        
        // 等待主循环线程结束
        if let Some(thread) = self.main_loop_thread.take() {
            if let Err(err) = thread.join() {
                error!("Desktop environment main loop thread panicked: {:?}", err);
            }
        }
        
        // 停止所有运行中的应用程序
        self.stop_all_apps()?;
        
        // 销毁桌面背景窗口
        if let Some(window_id) = self.desktop_background_window {
            self.graphics_subsystem.lock().map_err(|_| {
                DesktopEnvironmentError::OperationFailed
            })?
            .destroy_window(window_id)
            .map_err(|e| {
                DesktopEnvironmentError::GraphicsSubsystemError(e)
            })?;
            
            self.desktop_background_window = None;
        }
        
        info!("OriginOS-style Desktop Environment stopped successfully");
        Ok(())
    }
    
    // 启动应用程序
    pub fn launch_app(&self, app_id: &str) -> Result<u64, DesktopEnvironmentError> {
        let app_registry = self.app_registry.read().unwrap();
        
        // 检查应用程序是否存在
        let app_info = app_registry.get(app_id).ok_or(
            DesktopEnvironmentError::AppNotFound
        )?.clone();
        
        // 检查应用程序是否已经在运行
        { 
            let running_apps = self.running_apps.read().unwrap();
            if running_apps.contains_key(app_id) {
                let running_app = running_apps.get(app_id).unwrap();
                if running_app.state == AppState::Running {
                    // 应用程序已经在运行，激活它
                    self.activate_app(app_id)?;
                    return Ok(running_app.window_id);
                }
            }
        }
        
        // 创建应用程序窗口
        let window_id = self.graphics_subsystem.lock().map_err(|_| {
            DesktopEnvironmentError::OperationFailed
        })?
        .create_window(
            &app_info.name,
            100, 100, 
            800, 600
        ).map_err(|e| {
            DesktopEnvironmentError::GraphicsSubsystemError(e)
        })?;
        
        // 记录运行中的应用程序
        { 
            let mut running_apps = self.running_apps.write().unwrap();
            running_apps.insert(app_id.to_string(), RunningApp {
                app_id: app_id.to_string(),
                app_info: app_info.clone(),
                window_id,
                state: AppState::Running,
                process_id: None, // 在实际实现中，这里会启动进程并记录进程ID
            });
        }
        
        // 通知Kuikly服务应用程序启动
        self.kuikly_service.lock().map_err(|_| {
            DesktopEnvironmentError::OperationFailed
        })?
        .notify_app_launched(app_id, window_id)
        .map_err(|e| {
            DesktopEnvironmentError::KuiklyError(e)
        })?;
        
        info!("Launched application: {} (window: {})", app_id, window_id);
        
        Ok(window_id)
    }
    
    // 停止应用程序
    pub fn stop_app(&self, app_id: &str) -> Result<(), DesktopEnvironmentError> {
        let mut running_apps = self.running_apps.write().unwrap();
        
        // 检查应用程序是否在运行
        if let Some(mut running_app) = running_apps.remove(app_id) {
            running_app.state = AppState::Stopping;
            
            // 销毁应用程序窗口
            self.graphics_subsystem.lock().map_err(|_| {
                DesktopEnvironmentError::OperationFailed
            })?
            .destroy_window(running_app.window_id)
            .map_err(|e| {
                DesktopEnvironmentError::GraphicsSubsystemError(e)
            })?;
            
            // 通知Kuikly服务应用程序停止
            self.kuikly_service.lock().map_err(|_| {
                DesktopEnvironmentError::OperationFailed
            })?
            .notify_app_stopped(app_id)
            .map_err(|e| {
                DesktopEnvironmentError::KuiklyError(e)
            })?;
            
            info!("Stopped application: {}", app_id);
            
            Ok(())
        } else {
            Err(DesktopEnvironmentError::AppNotFound)
        }
    }
    
    // 停止所有运行中的应用程序
    fn stop_all_apps(&self) -> Result<(), DesktopEnvironmentError> {
        let app_ids: Vec<_> = {
            let running_apps = self.running_apps.read().unwrap();
            running_apps.keys().cloned().collect()
        };
        
        for app_id in app_ids {
            if let Err(err) = self.stop_app(&app_id) {
                warn!("Failed to stop application {}: {:?}", app_id, err);
            }
        }
        
        Ok(())
    }
    
    // 激活应用程序
    pub fn activate_app(&self, app_id: &str) -> Result<(), DesktopEnvironmentError> {
        let running_apps = self.running_apps.read().unwrap();
        
        // 检查应用程序是否在运行
        if let Some(running_app) = running_apps.get(app_id) {
            if running_app.state == AppState::Running {
                // 设置窗口焦点
                self.graphics_subsystem.lock().map_err(|_| {
                    DesktopEnvironmentError::OperationFailed
                })?
                .set_window_focus(running_app.window_id, true)
                .map_err(|e| {
                    DesktopEnvironmentError::GraphicsSubsystemError(e)
                })?;
                
                // 通知Kuikly服务应用程序被激活
                self.kuikly_service.lock().map_err(|_| {
                    DesktopEnvironmentError::OperationFailed
                })?
                .notify_app_activated(app_id, running_app.window_id)
                .map_err(|e| {
                    DesktopEnvironmentError::KuiklyError(e)
                })?;
                
                info!("Activated application: {}", app_id);
                
                Ok(())
            } else {
                Err(DesktopEnvironmentError::AppNotFound)
            }
        } else {
            Err(DesktopEnvironmentError::AppNotFound)
        }
    }
    
    // 检查桌面环境是否已初始化
    pub fn is_initialized(&self) -> bool {
        self.initialized
    }
    
    // 检查桌面环境是否正在运行
    pub fn is_running(&self) -> bool {
        self.running
    }
}

// 实现Drop trait，确保资源被正确清理
impl Drop for DesktopEnvironment {
    fn drop(&mut self) {
        let _ = self.stop();
    }
}

// 实现桌面环境窗口事件处理器
impl DesktopEnvironment {
    // 窗口创建事件处理
    pub fn on_window_created(
        &self,
        window_id: u64,
        title: &str,
        x: i32,
        y: i32,
        width: u32,
        height: u32
    ) -> Result<(), DesktopEnvironmentError> {
        // 检查是否是桌面背景窗口
        if let Some(desktop_window) = self.desktop_background_window {
            if window_id == desktop_window {
                info!("Desktop background window created: {}", window_id);
                return Ok(());
            }
        }
        
        // 检查是否是已知应用程序窗口
        let running_apps = self.running_apps.read().unwrap();
        for (app_id, app) in running_apps.iter() {
            if app.window_id == window_id {
                info!("Application window created: {}, app_id: {}", window_id, app_id);
                
                // 更新Dock项状态
                self.update_dock_for_app(app_id, true)?;
                
                // 通知Kuikly服务应用程序窗口创建
                self.kuikly_service.lock().map_err(|_| {
                    DesktopEnvironmentError::OperationFailed
                })?
                .notify_app_launched(app_id, window_id)
                .map_err(|e| {
                    DesktopEnvironmentError::KuiklyError(e)
                })?;
                
                return Ok(());
            }
        }
        
        info!("Unknown window created: {}, title: {}", window_id, title);
        
        // 为未知窗口创建临时应用记录
        let app_id = format!("unknown-app-{}", window_id);
        let app_info = AppInfo {
            app_id: app_id.clone(),
            name: title.to_string(),
            icon_path: "icons/default.png".to_string(),
            executable_path: "".to_string(),
            description: "Unknown application".to_string(),
            category: "Unknown".to_string(),
        };
        
        // 记录应用程序
        { 
            let mut running_apps = self.running_apps.write().unwrap();
            running_apps.insert(app_id.clone(), RunningApp {
                app_id: app_id.clone(),
                app_info: app_info.clone(),
                window_id,
                state: AppState::Running,
                process_id: None,
            });
        }
        
        // 通知Kuikly服务
        self.kuikly_service.lock().map_err(|_| {
            DesktopEnvironmentError::OperationFailed
        })?
        .notify_window_created(window_id, title, x, y, width, height)
        .map_err(|e| {
            DesktopEnvironmentError::KuiklyError(e)
        })?;
        
        Ok(())
    }
    
    // 窗口销毁事件处理
    pub fn on_window_destroyed(
        &self,
        window_id: u64
    ) -> Result<(), DesktopEnvironmentError> {
        // 检查是否是桌面背景窗口
        if let Some(desktop_window) = self.desktop_background_window {
            if window_id == desktop_window {
                info!("Desktop background window destroyed: {}", window_id);
                return Ok(());
            }
        }
        
        // 查找并移除对应的应用程序
        let app_id_opt: Option<String> = {
            let mut running_apps = self.running_apps.write().unwrap();
            
            // 查找应用程序
            let app_id_opt = running_apps.iter()
                .find(|(_, app)| app.window_id == window_id)
                .map(|(app_id, _)| app_id.clone());
            
            // 如果找到应用程序，将其移除
            if let Some(app_id) = &app_id_opt {
                running_apps.remove(app_id);
                
                // 更新Dock项状态
                self.update_dock_for_app(app_id, false)?;
                
                // 通知Kuikly服务应用程序停止
                self.kuikly_service.lock().map_err(|_| {
                    DesktopEnvironmentError::OperationFailed
                })?
                .notify_app_stopped(app_id)
                .map_err(|e| {
                    DesktopEnvironmentError::KuiklyError(e)
                })?;
            }
            
            app_id_opt
        };
        
        // 通知Kuikly服务窗口销毁
        self.kuikly_service.lock().map_err(|_| {
            DesktopEnvironmentError::OperationFailed
        })?
        .notify_window_destroyed(window_id)
        .map_err(|e| {
            DesktopEnvironmentError::KuiklyError(e)
        })?;
        
        if let Some(app_id) = app_id_opt {
            info!("Application window destroyed: {}, app_id: {}", window_id, app_id);
        } else {
            info!("Unknown window destroyed: {}", window_id);
        }
        
        Ok(())
    }
    
    // 窗口移动事件处理
    pub fn on_window_moved(
        &self,
        window_id: u64,
        x: i32,
        y: i32
    ) -> Result<(), DesktopEnvironmentError> {
        // 通知Kuikly服务窗口移动
        self.kuikly_service.lock().map_err(|_| {
            DesktopEnvironmentError::OperationFailed
        })?
        .notify_window_moved(window_id, x, y)
        .map_err(|e| {
            DesktopEnvironmentError::KuiklyError(e)
        })?;
        
        // 检查Dock栏自动隐藏逻辑
        if self.config.read().unwrap().auto_hide_dock {
            // 在实际实现中，这里会检查窗口是否靠近Dock栏
            // 并根据需要显示/隐藏Dock栏
        }
        
        info!("Window moved: {} to ({}, {})", window_id, x, y);
        
        Ok(())
    }
    
    // 窗口大小改变事件处理
    pub fn on_window_resized(
        &self,
        window_id: u64,
        width: u32,
        height: u32
    ) -> Result<(), DesktopEnvironmentError> {
        // 通知Kuikly服务窗口大小改变
        self.kuikly_service.lock().map_err(|_| {
            DesktopEnvironmentError::OperationFailed
        })?
        .notify_window_resized(window_id, width, height)
        .map_err(|e| {
            DesktopEnvironmentError::KuiklyError(e)
        })?;
        
        info!("Window resized: {} to {}x{}", window_id, width, height);
        
        Ok(())
    }
    
    // 窗口可见性改变事件处理
    pub fn on_window_visibility_changed(
        &self,
        window_id: u64,
        visible: bool
    ) -> Result<(), DesktopEnvironmentError> {
        // 通知Kuikly服务窗口可见性改变
        self.kuikly_service.lock().map_err(|_| {
            DesktopEnvironmentError::OperationFailed
        })?
        .notify_window_visibility_changed(window_id, visible)
        .map_err(|e| {
            DesktopEnvironmentError::KuiklyError(e)
        })?;
        
        // 更新Dock项状态（如果需要）
        let running_apps = self.running_apps.read().unwrap();
        for (app_id, app) in running_apps.iter() {
            if app.window_id == window_id {
                self.update_dock_for_app(app_id, visible)?;
                break;
            }
        }
        
        info!("Window visibility changed: {}, visible: {}", window_id, visible);
        
        Ok(())
    }
    
    // 窗口焦点改变事件处理
    pub fn on_window_focus_changed(
        &self,
        window_id: u64,
        focused: bool
    ) -> Result<(), DesktopEnvironmentError> {
        // 通知Kuikly服务窗口焦点改变
        self.kuikly_service.lock().map_err(|_| {
            DesktopEnvironmentError::OperationFailed
        })?
        .notify_window_focus_changed(window_id, focused)
        .map_err(|e| {
            DesktopEnvironmentError::KuiklyError(e)
        })?;
        
        // 如果窗口获得焦点，更新对应的应用程序状态
        if focused {
            let running_apps = self.running_apps.read().unwrap();
            for (app_id, app) in running_apps.iter() {
                if app.window_id == window_id {
                    self.kuikly_service.lock().map_err(|_| {
                        DesktopEnvironmentError::OperationFailed
                    })?
                    .notify_app_activated(app_id, window_id)
                    .map_err(|e| {
                        DesktopEnvironmentError::KuiklyError(e)
                    })?;
                    break;
                }
            }
        }
        
        info!("Window focus changed: {}, focused: {}", window_id, focused);
        
        Ok(())
    }
    
    // 更新Dock项状态
    fn update_dock_for_app(
        &self,
        app_id: &str,
        running: bool
    ) -> Result<(), DesktopEnvironmentError> {
        let mut dock_items = self.dock_items.write().unwrap();
        
        // 查找对应的Dock项
        for dock_item in dock_items.iter_mut() {
            if let DockItemType::App(id) = &dock_item.item_type {
                if id == app_id {
                    // 在实际实现中，这里会更新Dock项的运行状态
                    // 例如：显示/隐藏运行指示器、改变图标样式等
                    
                    // 这里只是记录日志
                    if running {
                        info!("Updated dock item for app {}: running", app_id);
                    } else {
                        info!("Updated dock item for app {}: not running", app_id);
                    }
                    
                    break;
                }
            }
        }
        
        Ok(())
    }
    
    // 设置桌面背景
    pub fn set_wallpaper(&mut self, wallpaper_path: &str) -> Result<(), DesktopEnvironmentError> {
        // 更新配置
        let mut config = self.config.write().unwrap();
        config.wallpaper_path = wallpaper_path.to_string();
        
        // 在实际实现中，这里会更新桌面背景窗口的内容
        info!("Wallpaper set to: {}", wallpaper_path);
        
        Ok(())
    }
    
    // 显示/隐藏Dock栏
    pub fn set_dock_visibility(&mut self, visible: bool) -> Result<(), DesktopEnvironmentError> {
        // 更新配置
        let mut config = self.config.write().unwrap();
        config.show_dock = visible;
        
        // 在实际实现中，这里会显示/隐藏Dock栏
        info!("Dock visibility set to: {}", visible);
        
        Ok(())
    }
    
    // 启用/禁用Dock栏自动隐藏
    pub fn set_dock_auto_hide(&mut self, auto_hide: bool) -> Result<(), DesktopEnvironmentError> {
        // 更新配置
        let mut config = self.config.write().unwrap();
        config.auto_hide_dock = auto_hide;
        
        info!("Dock auto-hide set to: {}", auto_hide);
        
        Ok(())
    }
    
    // 显示/隐藏桌面图标
    pub fn set_desktop_icons_visibility(&mut self, visible: bool) -> Result<(), DesktopEnvironmentError> {
        // 更新配置
        let mut config = self.config.write().unwrap();
        config.show_desktop_icons = visible;
        
        info!("Desktop icons visibility set to: {}", visible);
        
        Ok(())
    }
    
    // 启用/禁用动画效果
    pub fn set_animations_enabled(&mut self, enabled: bool) -> Result<(), DesktopEnvironmentError> {
        // 更新配置
        let mut config = self.config.write().unwrap();
        config.enable_animations = enabled;
        
        info!("Animations set to: {}", enabled);
        
        Ok(())
    }
    
    // 获取所有运行中的应用程序
    pub fn get_running_apps(&self) -> Vec<AppInfo> {
        let running_apps = self.running_apps.read().unwrap();
        running_apps.values()
            .filter(|app| app.state == AppState::Running)
            .map(|app| app.app_info.clone())
            .collect()
    }
    
    // 获取Dock项列表
    pub fn get_dock_items(&self) -> Vec<String> {
        let dock_items = self.dock_items.read().unwrap();
        dock_items.iter()
            .filter_map(|item| {
                if let DockItemType::App(app_id) = &item.item_type {
                    Some(app_id.clone())
                } else {
                    None
                }
            })
            .collect()
    }
    
    // 添加应用程序到Dock
    pub fn add_app_to_dock(&mut self, app_id: &str) -> Result<(), DesktopEnvironmentError> {
        // 检查应用程序是否存在
        let app_registry = self.app_registry.read().unwrap();
        if !app_registry.contains_key(app_id) {
            return Err(DesktopEnvironmentError::AppNotFound);
        }
        
        // 检查应用程序是否已经在Dock中
        let dock_items = self.dock_items.read().unwrap();
        if dock_items.iter().any(|item| {
            if let DockItemType::App(id) = &item.item_type {
                id == app_id
            } else {
                false
            }
        }) {
            return Err(DesktopEnvironmentError::OperationFailed);
        }
        
        // 添加应用程序到Dock
        let mut dock_items = self.dock_items.write().unwrap();
        let position = dock_items.len() as u32;
        
        dock_items.push(DockItem {
            item_type: DockItemType::App(app_id.to_string()),
            position,
            visible: true,
            hovered: false,
        });
        
        info!("Added application to dock: {}", app_id);
        
        Ok(())
    }
    
    // 从Dock移除应用程序
    pub fn remove_app_from_dock(&mut self, app_id: &str) -> Result<(), DesktopEnvironmentError> {
        // 查找并移除Dock项
        let mut dock_items = self.dock_items.write().unwrap();
        let initial_len = dock_items.len();
        
        dock_items.retain(|item| {
            if let DockItemType::App(id) = &item.item_type {
                id != app_id
            } else {
                true
            }
        });
        
        if dock_items.len() == initial_len {
            return Err(DesktopEnvironmentError::AppNotFound);
        }
        
        // 更新剩余Dock项的位置
        for (i, item) in dock_items.iter_mut().enumerate() {
            item.position = i as u32;
        }
        
        info!("Removed application from dock: {}", app_id);
        
        Ok(())
    }
}